package org.egedede.commons.ui;

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;

import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JPanel;

import org.egedede.commons.Resetable;

public class ResetableDialog extends JDialog {

	/**
	 * 
	 */
	private static final long serialVersionUID = 5676160711884652048L;
	public static final int OK = 0;
	public static final int CANCEL = 1;

	private JComponent panel = null;

	private final JButton ok;
	private final JButton cancel;

	private int value;

	private final GridBagLayoutBuilder layoutBuilder;

	public ResetableDialog() {
		super();
		this.setModal(true);
		final JComponent contentPane = new JPanel(new GridBagLayout());
		this.setContentPane(contentPane);
		layoutBuilder = new GridBagLayoutBuilder(contentPane, null);
		ok = new JButton(new AbstractAction("OK") {

			private static final long serialVersionUID = 860975759071332695L;

			public void actionPerformed(final ActionEvent e) {
				ResetableDialog.this.dispose();
				value = OK;
			}

		});
		cancel = new JButton(new AbstractAction("Cancel") {

			/**
			 * 
			 */
			private static final long serialVersionUID = -7215780314350437700L;

			public void actionPerformed(final ActionEvent e) {
				if (panel instanceof Resetable) {
					((Resetable) panel).reset();
				}
				value = CANCEL;
				ResetableDialog.this.dispose();
			}

		});

		layoutBuilder.addXY(ok, 0, 1);
		layoutBuilder.addXY(cancel, 1, 1);
	}

	public void setPanel(final JComponent panel) {
		this.panel = panel;
		layoutBuilder.setWeight(1, 1);
		layoutBuilder.setFill(GridBagConstraints.BOTH);
		layoutBuilder.addXYWH(this.panel, 0, 0, 2, 1);
		this.pack();
		super.setVisible(true);

	}

	public int getValue() {
		return value;
	}

}
